// 블로그 상세 페이지 — 본문은 RootTaleBlogPost(블록 JSON 렌더러)에 위임,
// 글씨 크기·문단 간격·이미지 설명도 공통 렌더러가 처리한다. bodyJson의 서식을 제거하지 않는다.
// 메타데이터는 어드민 SEO 패널(metaJson.seo) 값을 우선 적용.
// slug 변경 시: API가 옛 slug로도 글을 찾아 현재 slug로 응답 → 301 redirect.
import type { Metadata } from "next";
import { notFound, permanentRedirect } from "next/navigation";
import { RootTaleBlogPost } from "@roottale/cms-renderer-next/server";
import {
  buildPostMetadata,
  postRedirectPath,
} from "@roottale/cms-renderer-next/routes";
import { articleSchema } from "@roottale/cms-client/server";

import { getAllPosts, getPost } from "@/lib/blog";

const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL!;

export const revalidate = 1800;

type Props = { params: Promise<{ slug: string }> };

export async function generateStaticParams() {
  const posts = await getAllPosts();
  return posts.map((p) => ({ slug: p.slug }));
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const post = await getPost(slug);
  if (!post) return {};
  // 어드민 SEO 패널(metaJson.seo) override + self-canonical + avcd 구조(RSS
  // alternate·Twitter Card·og article 확장)까지 1줄로. modified/section/tags 는
  // 있는 만큼만 넘기면 됩니다 — 없으면 해당 필드만 생략.
  return buildPostMetadata(
    {
      ...post,
      modified: post.modified,
      section: post.category || undefined,
      tags: post.tags.map((t) => t.name),
    },
    // ADR-0105 — 주소는 플랫폼 원장(post.path)을 읽고, 없을 때만 이 라우트 기본값.
    { siteUrl: SITE_URL, path: post.path ?? `/blog/${post.slug}` },
  );
}

export default async function PostPage({ params }: Props) {
  const { slug } = await params;
  const post = await getPost(slug);
  if (!post) notFound();
  // 옛 slug 로 들어온 요청 → 현재 slug 로 301 (검색 순위 승계).
  const redirect = postRedirectPath(post, slug);
  if (redirect) permanentRedirect(redirect);

  // ADR-0105 — 정본 주소는 플랫폼 원장(post.path). 없을 때만 이 라우트 기본값.
  const url = `${SITE_URL}${post.path ?? `/blog/${post.slug}`}`;
  // avcd 구조 — BlogPosting + 확장 옵션(전부 선택, 있는 값만 채우면 됩니다).
  const jsonLd = articleSchema({
    type: "BlogPosting",
    id: `${url}#article`,
    headline: post.title,
    description: post.description,
    url,
    image: post.image ?? undefined,
    datePublished: post.date,
    dateModified: post.modified,
    authorName: post.authorName,
    authorUrl: post.authorSlug
      ? `${SITE_URL}/blog/author/${post.authorSlug}`
      : undefined,
    publisherName: "예시 사이트",
    section: post.category || undefined,
    inLanguage: "ko",
  });

  return (
    <main>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />
      <h1>{post.title}</h1>
      <RootTaleBlogPost
        apiKey={process.env.ROOTTALE_API_KEY!}
        baseUrl={process.env.ROOTTALE_API_BASE}
        slugOrId={post.id}
        showTitle={false}
        showTableOfContents
        tocPosition="inline"
        theme={null}
        footerPatternPresentation={null}
        relatedPostsCount={3}
        // H1 위 카테고리 링크. breadcrumb 없이도 독립적으로 사용할 수 있습니다.
        categoryHref={(category) => `/blog/categories/${encodeURIComponent(category)}`}
        // opt-in — 시각 브레드크럼 + BreadcrumbList JSON-LD. siteUrl 없으면
        // 시각 브레드크럼만(JSON-LD 미emit).
        breadcrumb={{ siteUrl: SITE_URL }}
      />
    </main>
  );
}
